<template>
  <div class="template">
    <div class="page-head">
      <div class="page-title">数据模板</div>
      <div class="page-tool">
        <div class="tool-btn" @click="open('add')">新增数据模板</div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-table :data="tableData" stripe border :fit="true" :height="$tableHeight">
          <el-table-column
            prop="name"
            :show-overflow-tooltip="true"
            label="业务模板名称"
          >
          </el-table-column>

          <el-table-column
            prop="cnc"
            width="420"
            label="CNC类型"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="{ row }">
              <div>
                {{ cncSel.find((s) => s.k == row.cnc).v }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            :show-overflow-tooltip="true"
            label="备注"
            prop="remark"
          >
          </el-table-column>

          <el-table-column label="操作" align="center" width="238">
            <template slot-scope="{ row }">
              <div class="operation-col">
                <div class="txt-btn ope-btn" @click="toConfig(row)">
                  <el-tooltip
                    effect="dark"
                    content="上传服务器配置"
                    placement="top-start"
                  >
                    <img src="~assets/img/nupload.png" alt="" />
                  </el-tooltip>
                </div>
                <div class="txt-btn ope-btn" @click="toCalc(row)">
                  <el-tooltip
                    effect="dark"
                    content="计算点位配置"
                    placement="top-start"
                  >
                    <img src="~assets/img/points.png" alt="" />
                  </el-tooltip>
                </div>
                <div class="txt-btn ope-btn" @click="openParam(row)">
                  <el-tooltip
                    effect="dark"
                    content="参数选择"
                    placement="top-start"
                  >
                    <img src="~assets/img/data.png" alt="" />
                  </el-tooltip>
                </div>
                <div class="txt-btn ope-btn" @click="toDetail(row)">
                  <el-tooltip
                    effect="dark"
                    content="数据详情"
                    placement="top-start"
                  >
                    <img src="~assets/img/watch.png" alt="" />
                  </el-tooltip>
                </div>
                <div class="txt-btn ope-btn" @click="open('update', row)">
                  <el-tooltip
                    effect="dark"
                    content="编辑模板"
                    placement="top-start"
                  >
                    <img src="~assets/img/edit.png" alt="" />
                  </el-tooltip>
                </div>
                <div class="txt-btn" @click="doDelete(row)">
                  <el-tooltip
                    effect="dark"
                    content="删除"
                    placement="top-start"
                  >
                    <img src="~assets/img/delete.png" alt="" />
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
          @sizeChange="getSizePage"
        />
      </div>
    </div>

    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="370px"
      :title="model.type === 'add' ? '新增数据模板' : '修改数据模板'"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="模板名称" class="required">
            <el-input
              name="templateName"
              placeholder="请输入模板名称"
              v-model="form.name"
              v-validate="'required'"
            />
            <div
              v-show="errors.has('templateName')"
              class="el-form-item__error"
            >
              {{ errors.first("templateName") }}
            </div>
          </el-form-item>
          <el-form-item label="CNC类型" label-position="left" class="required">
            <el-select
              v-model="form.cnc"
              name="cnc_name"
              placeholder="请选择CNC类型"
              v-validate="'required'"
            >
              <el-option
                v-for="item in cncSel"
                :key="item.k"
                :label="item.v"
                :value="item.k"
              >
              </el-option>
            </el-select>
            <div v-show="errors.has('cnc_name')" class="el-form-item__error">
              {{ errors.first("cnc_name") }}
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" maxlength="128" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button
          v-if="model.type === 'add'"
          key="add"
          type="primary"
          @click="openParam()"
        >
          下一步
        </el-button>
        <el-button
          v-if="model.type === 'update'"
          key="update"
          type="primary"
          @click="submit"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>确定删除该条数据？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="asyncDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 穿梭弹窗 -->
    <param-dialog
      v-if="paramVisable"
      :cnc="form.cnc"
      :template_id="id"
      :rememberActive="rememberActive"
      :rememberIds="rememberIds"
      @cancel="paramCancel"
      @sure="paramSure"
    />

  </div>
</template>

<script>
import { format } from "silly-datetime";
import * as api from "@/api";
import { limit } from "@/consts/consts";
import { templateKey } from "@/consts/formKey";
import paginaTion from "@/components/libs/paginaTion";
import paramDialog from "@/components/views/template/paramDialog";
import confDialog from "@/components/views/template/confDialog";

export default {
  components: {
    paginaTion,
    paramDialog,
    confDialog,
  },

  data() {
    return {
      limit,
      total: 0,
      offset: 0,
      tableData: [],
      cncSel: [],
      format,
      search: "",
      model: {
        type: "add",
        visible: false,
      },
      id: "",
      form: {
        ...templateKey,
      },
      property: [],
      rememberIds: [],
      rememberActive: '0',
      server: {},
      visibility: false,
      paramVisable: false,
    };
  },

  methods: {
  
    toCalc(row) {
      this.$router.push({
        name: "calculation",
        query: {
          id: row.template_id,
          name: row.name,
          cnc: row.cnc,
          cnc_name: this.cncSel.find((s) => s.k == row.cnc).v,
        },
      });
    },
    doDelete(row) {
      this.id = row.template_id;
      this.visibility = true;
    },
    open(type, row = null) {
      this.model.type = type;
      if (row) {
        for (const k in templateKey) {
          this.form[k] = row[k];
        }
        this.id = row.template_id;
      } else {
        this.id = "";
        this.form = { ...templateKey };
        this.server = {}
        this.rememberIds = []
        this.property = []
        setTimeout(this.$validator.reset, 100);
      }

      this.model.visible = true;
    },

    getChangePage(val) {
      sessionStorage.setItem('templateCurPage', val.offset)
      this.offset = val.offset;
      this.getList();
    },

    getSizePage(val) {
      this.offset = 0
      this.getList();
    },

    close() {
      this.model.visible = false;
      this.paramVisable = false;
    },

    openParam(row = null) {
      if (row) {
        this.model.type = "update"
        this.id = row.template_id;
        this.paramVisable = true;
      } else {
        this.$validator.validateAll().then((valid) => {
          if (valid) {
            this.paramVisable = true;
            this.model.visible = false;
          } else {
            this.$message.warning("有信息未填写正确");
          }
        });
      }
    },

    paramCancel([e, active]) {
      this.paramVisable = false
      if (e === '上一步') {
        this.rememberActive = active
        this.model.visible = true
      }
      this.model.type = "add"
    },

    paramSure([e, active]) {
      this.property = [...e]
      this.rememberIds = [...e]
      if (this.id) {
        this.updateProperty(this.property, this.id);
      } else {
        this.rememberActive = active
        this.paramVisable = false
      }

      if (this.model.type === "add") {
        this.add();
      }
      this.model.type = "add"
    },


    toDetail(row) {
      this.$router.push({
        name: "templateDetail",
        query: {
          id: row.template_id,
          name: row.name,
          cnc: row.cnc,
          cnc_name: this.cncSel.find((s) => s.k == row.cnc).v,
        },
      });
    },
    toConfig(row) {
      this.$router.push({
        name: "serverConfig",
        query: {
          id: row.template_id,
          name: row.name,
          cnc: row.cnc,
          cnc_name: this.cncSel.find((s) => s.k == row.cnc).v,
        },
      });
    },




    // 下拉列表
    async downList(type) {
      const { code, data } = await api.dropdown(this).downList({
        type,
      });
      if (code === 0) {
        this[`${type}Sel`] = data;
        this.getList();
      }
    },

    // 列表
    async getList() {
      const { code, data, total } = await api.template(this).getList({
        offset: this.offset,
        limit: this.limit,
        name: this.search,
      });
      if (code === 0) {
        this.tableData = data
        this.total = total

        this.rememberIds = []
        this.server = {}
        this.close()
      }
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.update();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },

    async update() {
      const { code } = await api.template(this).update(this.form, this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.getList();
      }
    },

    async add() {
      const { code } = await api.template(this).add({
        template: this.form,
        property: this.property,
      });
      if (code === 0) {
        this.$message.success("操作成功");
        this.getList();
      }
    },

    async asyncDelete() {
      const { code } = await api.template(this).delete(this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.id = "";
        this.visibility = false;
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit;
          }
        }
        this.getList();
      }
    },

    async updateConfig() {
      const { code } = await api
        .template(this)
        .updateConfig(this.server, this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.id = "";
        this.visibility = false;
        this.getList();
      }
    },

    async updateProperty() {
      const { code } = await api.template(this).updateProperty(
        {
          property_id: this.property,
        },
        this.id
      );
      if (code === 0) {
        this.$message.success("操作成功");
        this.id = "";
        this.visibility = false;
        this.getList();
        this.paramCancel();
      }
    },
  },
  created() {
    let curPage = sessionStorage.getItem('templateCurPage')
    this.offset = +curPage
    this.downList("cnc");
  },
};
</script>

<style lang="stylus">
.template {
}
</style>